import 'package:ac/common/ac_pv_manager.dart';
import 'package:ac/data/ac_user_manager.dart';
import 'package:ac/model/ac_blogger_model.dart';
import 'package:flutter_easyloading/flutter_easyloading.dart';
import 'package:get/get.dart';
import 'package:image_picker/image_picker.dart';
import 'package:permission_handler/permission_handler.dart';

import 'ac_publish_state.dart';

class AcPublishLogic extends GetxController {
  final AcPublishState state = AcPublishState();

  Future<void> addImage() async {
    PermissionStatus status = await Permission.photos.request();
    if (!status.isGranted) {
      EasyLoading.showToast("You have not authorised this permission.");
      return;
    }
    final ImagePicker picker = ImagePicker();
    final XFile? image = await picker.pickImage(source: ImageSource.gallery);
    if(image != null){
      state.imageList.add(image.path);
    }
  }

  void deleteImage(int index) {
    state.imageList.removeAt(index);
  }

  void publish() async{
    if(state.titleController.text.isEmpty){
      EasyLoading.showToast("title can not be empty");
      return;
    }
    if (state.contentController.text.isEmpty || state.imageList.isEmpty) {
      EasyLoading.showToast("Images and content are required！");
      return;
    }
    LogPvManger.stat(page: LogPages.publishPage);

    EasyLoading.show(status: "posting...", maskType: EasyLoadingMaskType.black);
    await Future.delayed(const Duration(milliseconds: 1500));
    EasyLoading.dismiss();
    var map = {
      'title': state.titleController.text,
      'content': state.contentController.text,
      'likes': 0,
      'isLiked': false,
      'mainImage': state.imageList.first,
      'images': state.imageList,
      'comment': [],
    };
    Post post = Post.fromJson(map);
    AcUserManager.publishPost(post);
    Get.back();
    EasyLoading.showSuccess("post success");
  }
}
